package com.hwl.security.handler;

import com.hwl.commonutils.result.RespBean;
import com.hwl.commonutils.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenLogoutHandler implements LogoutHandler {

    private final TokenManager tokenManager;
    private final RedisTemplate<String, Object> redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate<String, Object> redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication a) {
        String token = request.getHeader("token");
        if (token != null) {
            String username = tokenManager.getUserFromToken(token);
            //清空当前用户缓存中的权限数据
            redisTemplate.delete(username);
        }
        ResponseUtil.out(response, RespBean.ok());
    }
}
